package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *
 * 通联天下
 * 可发送多条短信，号码中间用，隔开
 * Get: 最大支持 300，
 * Post: 最大支持 2000
 *
 */
public class SmsApiTLTX extends GateWayHttpAbstract
{

    public SmsApiTLTX(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        HashMap<String,String> header = Maps.newHashMap();
        header.put("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        Map<String,Object> params = Maps.newHashMap();
        params.put("uid",paramsMaps.get("uid"));
        params.put("auth", DigestUtils.md5Hex(paramsMaps.get("account") + paramsMaps.get("passwd")));
        params.put("mobile",mt.getPhone());
        String content = "";
        try{
            content = URLEncoder.encode(mt.getSmsContent(),"utf-8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            logger.error("网关:{},手机：{},内容：{}，内容编码错误。", this.gateWayID, mt.getPhone(), mt.getSmsContent());
        }
        params.put("msg",content);
        params.put("encode","utf-8");
        params.put("expid",paramsMaps.get("expid")); //扩展码
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/hy/", Joiner.on("&").withKeyValueSeparator("=").join(params), header);
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        List<SMSSRMessage> resultList = Lists.newArrayList();
        SMSSRMessage message = initGatewayResultMessage(result, mt, ",");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        if(StringUtils.equals(message.getResult(), "F10199")) {
            if (result.contains(",")) {
                String[] data = result.split(",");
                resultCode = data[0];
                resultMessage = data[0];
                taskid = data[1];
            } else {
                resultCode = result;
                resultMessage = result;
            }
            message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
            resultList.add(message);
        }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            String[] lines = text.split(";");
            for (int i = 0; i < lines.length; i++) {
                String[] data = lines[i].split(",");
                SMSRTMessage smsRtMessage = initSmsRtMessage(data[1], data[2], data[2], data[3], "DELIVRD");
                rtList.add(smsRtMessage);
            }
        }
        return new SmsHttpMsgResponse("0");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        Map<String,String> map = Maps.newHashMap();
        if (StringUtils.isNotBlank(text)) {
            String[] lines = text.split("\n");
            for (int i = 0; i < lines.length; i++) {
                String[] data = lines[i].split("##");
                SMSMOMessage sMSMOMessage = new SMSMOMessage();
                sMSMOMessage.setGateWayID(gateWayID);
                String conetent = "";
                try {
                    conetent = URLDecoder.decode(data[3],"GBK");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                sMSMOMessage.setMsgContent(conetent);
//                sMSMOMessage.setMsgid(data.getString("moid"));
                sMSMOMessage.setPhone(data[2]);
                sMSMOMessage.setSenttime(data[0]);
    //                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                sMSMOMessage.setUuid(UUID.randomUUID().toString());
                moList.add(sMSMOMessage);
            }
        }
        return new SmsHttpMsgResponse("0");
    }

    @Override
    public String queryReport(String jsonText) {
        Map<String,String> params = Maps.newHashMap();
        params.put("uid",paramsMaps.get("uid"));
        String preSign = paramsMaps.get("account") + paramsMaps.get("passwd");
        String auth = DigestUtils.md5Hex(preSign);
        params.put("auth", auth);
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/hy/rpt", Joiner.on("&").withKeyValueSeparator("=").join(params),null);
//        logger.info("通道：{}，主动获取报告状态，结果：{}",this.gateWayID, result);
        if (result.contains(",")) {
            return result;
        }
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        Map<String,String> params = Maps.newHashMap();
        params.put("uid", paramsMaps.get("uid"));
        params.put("auth", DigestUtils.md5Hex(paramsMaps.get("account") + paramsMaps.get("passwd")));
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/hy/mo", Joiner.on("&").withKeyValueSeparator("=").join(params),null);
//        logger.info("通道：{}，主动获取上行，结果：{}",this.gateWayID, result);
        if (result.contains(",")) {
            return result;
        }
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("uid",paramsMaps.get("uid"));
        String preSign = paramsMaps.get("account") + paramsMaps.get("passwd");
        String auth = DigestUtils.md5Hex(preSign);
//        params.put("auth", DigestUtils.md5Hex(paramsMaps.get("account") + paramsMaps.get("passwd")));
        params.put("auth", auth);
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/hy/m", Joiner.on("&").withKeyValueSeparator("=").join(params),null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        if (Integer.parseInt(result) > 0) {
            return "余额：" + result;
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
        String params = "{\"uid\":\"90006\",\"account\":\"yhxx\",\"passwd\":\"#7#m2@6\",\"apiUrl\":\"http://111.231.69.46:18083\",\"expid\":\"0\"}";
        SmsApiTLTX api = new SmsApiTLTX("ZY",params);
//        String balance = api.balance();
        String sign = DigestUtils.md5Hex("hyxx#7#m2@6");
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18268846802");
        message.setId("test123456");
        message.setSmsContent("【千橡科技】你的短信验证码是123456");
//        api.doSend(message);
        String a = "2018-04-02 17:05:09,600020057,18268846802,DELIVRD;2018-04-02 17:05:09,600020057,18268846802,DELIVRD;2018-04-02 17:33:20,600020058,18268846802,XA:0004;2018-04-02 17:33:20,600020058,18268846802,XA:0004;";
        api.parseReport(a,Lists.<SMSRTMessage>newArrayList());

//        System.out.println(DigestUtils.md5Hex("testmima20120701231212"));
    }
    
}